package com.unknownman.block.rabbitmq.reciever;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;

@Slf4j
public class TestTopicReceiver{

    /**
     * 如下配置，如果没有exchange或者queue那么会自动创建
     * @param message
     * @param channel
     * @param deliveryTag
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "${spring.application.group:}testQueue", durable = "true"),
        exchange = @Exchange(value = "${spring.application.group:}testExchange", type = "topic", ignoreDeclarationExceptions = "true"),
        key = "${spring.application.group:}testTopic"
    ))
    @RabbitHandler
    public void onMessage(Message message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws Exception{

        try{
            log.info("message={},channel={}", message, channel);
        }catch (Exception e){
            log.info("拒收！{}",deliveryTag);
            channel.basicReject(deliveryTag,true); // 发生异常情况一定要拒收
        }
    }
}
